<template>
	<view class="page">
		<view class="chat-container">
			<!-- 操作栏 -->
			<view class="action-bar">
				<view class="action-item" @click="clearChatHistory">
					<text class="action-text">清空聊天</text>
				</view>
				
				<!-- 模型选择 -->
				<view class="action-item model-selector" @click="showModelSelector = true">
					<text class="action-text">{{ selectedModel }}</text>
				</view>
				
				<!-- 连接状态指示器 -->
				<view class="connection-status">
					<view :class="['status-dot', isConnected ? 'connected' : 'disconnected']"></view>
					<text class="status-text">{{ isConnected ? '已连接' : '未连接' }}</text>
				</view>
			</view>
			
			<!-- 聊天消息列表 -->
			<scroll-view 
				scroll-y="true" 
				class="chat-list" 
				:scroll-top="scrollTop"
				:scroll-with-animation="true"
				:show-scrollbar="false"
				ref="chatScrollView"
			>
				<view v-for="(item, index) in chatList" :key="index" class="message-item">
					<view :class="['message-content', item.isUser ? 'user-message' : 'ai-message']">
						<view class="avatar">
							<template v-if="item.isUser">
								<include-svg src="/static/avatar/user-avatar.svg"></include-svg>
							</template>
							<template v-else>
								<include-svg src="/static/avatar/ai-avatar.svg"></include-svg>
							</template>
						</view>
						<view class="message-bubble">
							<view class="message-text">{{ item.content }}</view>
						</view>
					</view>
				</view>
				
				<!-- 正在输入指示器 -->
				<view v-if="isAiTyping" class="message-item">
					<view class="message-content ai-message">
						<view class="avatar">
							<include-svg src="/static/avatar/ai-avatar.svg"></include-svg>
						</view>
						<view class="message-bubble">
							<view class="typing-indicator">
								<view class="dot"></view>
								<view class="dot"></view>
								<view class="dot"></view>
							</view>
						</view>
					</view>
				</view>
				
				<view class="placeholder" style="height: 20px;"></view>
			</scroll-view>
			
			<!-- 输入区域 -->
			<view class="input-area">
				<input 
					type="text" 
					v-model="inputMessage" 
					placeholder="请输入您的问题" 
					class="message-input"
					@confirm="sendMessage"
					:disabled="!isConnected || isAiTyping"
				/>
				<button 
					class="send-btn" 
					@click="sendMessage" 
					:disabled="!inputMessage.trim() || !isConnected || isAiTyping"
				>发送</button>
			</view>
		</view>
		
		<!-- 模型选择弹窗 -->
		<view v-if="showModelSelector" class="model-popup">
			<view class="model-popup-mask" @click="showModelSelector = false"></view>
			<view class="model-popup-content">
				<view class="model-popup-title">选择AI模型</view>
				<scroll-view scroll-y="true" class="model-list">
					<view 
						v-for="(model, index) in availableModels" 
						:key="index" 
						class="model-item"
						:class="{ 'active': model.id === selectedModel }"
						@click="selectModel(model.id)"
					>
						<text class="model-name">{{ model.name }}</text>
						<text class="model-desc">{{ model.description }}</text>
					</view>
				</scroll-view>
				<button class="confirm-btn" @click="showModelSelector = false">确认</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, nextTick, watch, onMounted, onUnmounted } from 'vue';
	import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
	import wsAiService from "/common/api/wsAi.js";
	import IncludeSvg from "/components/IncludeSvg.vue";
	
	// 聊天数据
	const chatList = ref([
		{
			isUser: false,
			content: '你好，我是AI助手，有什么可以帮助你的？'
		}
	]);
	
	// 输入框内容
	const inputMessage = ref('');
	
	// 滚动位置
	const scrollTop = ref(0);
	
	// WebSocket连接状态
	const isConnected = ref(false);
	
	// AI是否正在输入
	const isAiTyping = ref(false);
	
	// 当前AI回复内容
	let currentAiReply = '';
	
	// 模型选择相关
	const showModelSelector = ref(false);
	const selectedModel = ref('gpt-3.5-turbo');
	
	// 可用模型列表
	const availableModels = [
		{
			id: 'ep-20250204190620-9n94t',
			name: 'GPT-3.5 Turbo',
			description: '快速响应，适合一般对话'
		},
		{
			id: 'ep-20250204190620-9n94t',
			name: 'GPT-4',
			description: '更强大，适合复杂任务'
		},
		{
			id: 'ep-20250204190620-9n94t',
			name: 'GPT-4 Turbo',
			description: '最新模型，性能更强'
		}
	];
	
	// 选择模型
	const selectModel = (modelId) => {
		selectedModel.value = modelId;
	};
	
	// 初始化WebSocket服务
	const initWebSocket = async () => {
		try {
			await wsAiService.initAiWsService({
				onMessage: handleAiMessage,
				onConnected: () => {
					isConnected.value = true;
					uni.showToast({
						title: 'AI助手已连接',
						icon: 'success'
					});
				},
				onDisconnected: () => {
					isConnected.value = false;
					uni.showToast({
						title: 'AI助手已断开连接',
						icon: 'none'
					});
				},
				onError: (error) => {
					console.error('AI助手连接错误:', error);
					uni.showToast({
						title: '连接错误，请稍后再试',
						icon: 'none'
					});
				}
			});
		} catch (error) {
			console.error('初始化WebSocket连接失败:', error);
			uni.showToast({
				title: '连接失败，请稍后再试',
				icon: 'none'
			});
		}
	};
	
	// 处理AI消息
	const handleAiMessage = (message, isEnd, isError) => {
		if (isError) {
			// 显示错误消息
			chatList.value.push({
				isUser: false,
				content: message || '发生错误，请稍后再试'
			});
			isAiTyping.value = false;
			return;
		}
		
		if (isAiTyping.value) {
			// 累加消息内容
			currentAiReply += message;
			
			if (isEnd) {
				// 消息接收完毕，显示完整回复
				chatList.value.push({
					isUser: false,
					content: currentAiReply
				});
				currentAiReply = '';
				isAiTyping.value = false;
			}
			
			// 滚动到底部
			scrollToBottom();
		}
	};
	
	// 发送消息
	const sendMessage = async () => {
		if (!inputMessage.value.trim() || !isConnected.value || isAiTyping.value) return;
		
		// 添加用户消息
		const userMessage = inputMessage.value;
		chatList.value.push({
			isUser: true,
			content: userMessage
		});
		
		// 清空输入
		inputMessage.value = '';
		
		// 滚动到底部
		await scrollToBottom();
		
		// 设置AI正在输入状态
		isAiTyping.value = true;
		currentAiReply = '';
		
		// 准备配置选项
		const config = {
			model: selectedModel.value,
			temperature: 0.7,
			max_tokens: 2000,
			stream: true
		};
		
		// 发送消息到WebSocket服务
		try {
			await wsAiService.sendAiChatMessage({
				message: userMessage,
				config: config
			});
		} catch (error) {
			console.error('发送消息失败:', error);
			isAiTyping.value = false;
			
			// 显示错误提示
			chatList.value.push({
				isUser: false,
				content: '发送消息失败，请检查网络连接'
			});
			
			// 滚动到底部
			scrollToBottom();
		}
	};
	
	// 清空聊天记录
	const clearChatHistory = async () => {
		uni.showModal({
			title: '提示',
			content: '确定要清空所有聊天记录吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						await wsAiService.clearAiChatSession();
						
						// 重置为初始欢迎消息
						chatList.value = [{
							isUser: false,
							content: '你好，我是AI助手，有什么可以帮助你的？'
						}];
						
						uni.showToast({
							title: '已清空聊天记录',
							icon: 'success'
						});
					} catch (error) {
						console.error('清空聊天记录失败:', error);
						uni.showToast({
							title: '清空失败，请稍后再试',
							icon: 'none'
						});
					}
				}
			}
		});
	};
	
	// 滚动到底部方法
	const scrollToBottom = async () => {
		await nextTick();
		const query = uni.createSelectorQuery().in(this);
		query.select('.chat-list').boundingClientRect(data => {
			if (data) {
				scrollTop.value = data.height * 2; // 使用足够大的值确保滚动到底部
			}
		}).exec();
	};
	
	// 监听聊天列表变化，自动滚动到底部
	watch(chatList, () => {
		scrollToBottom();
	}, { deep: true });
	
	// 页面显示时连接WebSocket
	onShow(() => {
		scrollToBottom();
		
		// 如果未连接，则进行连接
		if (!isConnected.value) {
			initWebSocket();
		}
	});
	
	// 页面隐藏时断开WebSocket
	onHide(() => {
		if (isConnected.value) {
			wsAiService.closeAiWsService();
			isConnected.value = false;
		}
	});
	
	// 组件卸载时关闭WebSocket连接
	onUnmounted(() => {
		wsAiService.closeAiWsService();
	});
	
	// 页面加载
	onLoad(() => {
		// 设置导航栏标题
		uni.setNavigationBarTitle({
			title: 'AI助手 (WebSocket)'
		});
		
		// 设置导航栏颜色
		uni.setNavigationBarColor({
			frontColor: '#000000',
			backgroundColor: '#ffffff'
		});
		
		// 初始化WebSocket连接
		initWebSocket();
	});
</script>

<style>
	.page {
		width: 100vw;
		height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}
	
	.chat-container {
		display: flex;
		flex-direction: column;
		height: 100%;
		position: relative;
		background-color: #f5f5f5;
	}
	
	.action-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background-color: #ffffff;
		border-bottom: 1px solid #eee;
	}
	
	.action-item {
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		background-color: #f0f0f0;
		margin-right: 10rpx;
	}
	
	.model-selector {
		background-color: #f0f9ff;
		border: 1px solid #91caff;
	}
	
	.action-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.connection-status {
		display: flex;
		align-items: center;
	}
	
	.status-dot {
		width: 10rpx;
		height: 10rpx;
		border-radius: 50%;
		margin-right: 10rpx;
	}
	
	.connected {
		background-color: #07c160;
	}
	
	.disconnected {
		background-color: #ff5a5f;
	}
	
	.status-text {
		font-size: 24rpx;
		color: #666;
	}
	
	.chat-list {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
	}
	
	.message-item {
		margin-bottom: 30rpx;
	}
	
	.message-content {
		display: flex;
		align-items: flex-start;
	}
	
	.user-message {
		flex-direction: row-reverse;
	}
	
	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		overflow: hidden;
		margin: 0 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	}
	
	.avatar image {
		width: 100%;
		height: 100%;
	}
	
	.message-bubble {
		max-width: 70%;
		padding: 20rpx 30rpx;
		border-radius: 10rpx;
		word-break: break-all;
	}
	
	.user-message .message-bubble {
		background-color: #007AFF;
		color: #fff;
		border-top-right-radius: 0;
	}
	
	.ai-message .message-bubble {
		background-color: #fff;
		color: #333;
		border-top-left-radius: 0;
	}
	
	.typing-indicator {
		display: flex;
		align-items: center;
		height: 40rpx;
	}
	
	.typing-indicator .dot {
		width: 10rpx;
		height: 10rpx;
		background-color: #999;
		border-radius: 50%;
		margin: 0 3rpx;
		animation: typingAnimation 1.5s infinite ease-in-out;
	}
	
	.typing-indicator .dot:nth-child(1) {
		animation-delay: 0s;
	}
	
	.typing-indicator .dot:nth-child(2) {
		animation-delay: 0.3s;
	}
	
	.typing-indicator .dot:nth-child(3) {
		animation-delay: 0.6s;
	}
	
	@keyframes typingAnimation {
		0%, 60%, 100% {
			transform: translateY(0);
		}
		30% {
			transform: translateY(-4rpx);
		}
	}
	
	.input-area {
		padding: 20rpx;
		background-color: #fff;
		border-top: 1px solid #eee;
		display: flex;
		align-items: center;
		position: sticky;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
	}
	
	.message-input {
		flex: 1;
		height: 80rpx;
		background-color: #f0f0f0;
		border-radius: 40rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
		margin-right: 20rpx;
	}
	
	.send-btn {
		width: 140rpx;
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0;
	}
	
	.send-btn:active {
		background-color: #0056b3;
	}
	
	.send-btn[disabled] {
		background-color: #cccccc;
		color: #f5f5f5;
	}
	
	/* 模型选择弹窗样式 */
	.model-popup {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 999;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.model-popup-mask {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
	}
	
	.model-popup-content {
		width: 80%;
		max-height: 70%;
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		position: relative;
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}
	
	.model-popup-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
		text-align: center;
	}
	
	.model-list {
		flex: 1;
		overflow-y: auto;
		margin-bottom: 20rpx;
	}
	
	.model-item {
		padding: 20rpx;
		border-bottom: 1px solid #eee;
		display: flex;
		flex-direction: column;
	}
	
	.model-item.active {
		background-color: #f0f9ff;
		border-left: 4rpx solid #007AFF;
	}
	
	.model-name {
		font-size: 28rpx;
		font-weight: bold;
		margin-bottom: 5rpx;
	}
	
	.model-desc {
		font-size: 24rpx;
		color: #999;
	}
	
	.confirm-btn {
		width: 100%;
		height: 80rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style> 